package com.woniu.zsd.user.consumer;


import com.woniu.zsd.common.util.RedisKey;
import com.woniu.zsd.common.util.SMSUtil;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class SendSignUpCodeConsumer {
    @Resource
    private SMSUtil smsUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @RabbitHandler
    @RabbitListener(bindings = @QueueBinding(exchange = @Exchange(name = "send.signup.code.ex", type = "direct"),
            value = @Queue(name = "send.signup.code.queue"),
            key = "send.signup.code"))
    public void sendSignUpCode(String phone) throws Exception {
//            String code = smsUtil.sendCode(phone);
        String code = String.valueOf(Math.random()).substring(2, 6);
        //保存一个flag在redis中用于判断一分钟内是否发送过验证码
        stringRedisTemplate.opsForValue().set(RedisKey.signUpCodeSendOneMinLimitKey(phone), "true", 60, TimeUnit.SECONDS);
        //保存验证码到redis并设置过期时间为300秒/5分钟
        stringRedisTemplate.opsForValue().set(RedisKey.signUpCodeKey(phone), code, 5,TimeUnit.MINUTES);
        //保存发送次数到redis并设置过期时间为
        if (stringRedisTemplate.hasKey(RedisKey.sendCodeCountKey(phone))) {
            stringRedisTemplate.opsForValue().increment(RedisKey.sendCodeCountKey(phone));
        } else {
            stringRedisTemplate.opsForValue().set(RedisKey.sendCodeCountKey(phone), "1", 1, TimeUnit.HOURS);
        }


    }
}
